angular.module('app.services', [])

    .factory('SystemService', function ($q, $http, hostip) {
        let user = null;
        let uid = null;
        return {
            getUser: function () {
                let userCache = null;

                if (!localStorage.user) {
                    userCache = null;
                }
                else {
                    userCache = JSON.parse(localStorage.user);
                }

                //判断是否存在用户缓存
                if (user && userCache) {
                    //判断本地缓存和session或者localstorage里面的用户信息是否相同
                    if (user._id !== userCache._id) {
                        user = userCache;
                    }
                } else if (!user && userCache) {
                    user = userCache;
                }
                return user;
            },
            setUser: function (newUser) {
                user = newUser;
                localStorage.user = JSON.stringify(newUser);
            },

            getUID: function () {
                if (!user) {
                    user = JSON.parse(localStorage.user);
                }
                return user._id;
            },

            setUID: function (newUID) {
                uid = newUID;
                localStorage.uid = newUID;
            },
            getHostIP: function () {
                // return window.location.protocol + '//' + window.location.host;
                return hostip;
            }

        }
    })

    .service('UserService', function ($q, $http, SystemService) {
        this.login = function (user) {
            let param = {
                "studentID": user.studentID,
                "pwdText": user.pwdText

            }
            console.log(param);
            var deferred = $q.defer();//生成deferred异步对象
            $http.post(SystemService.getHostIP() + '/users/login', param)//封装好的param传给后台
                .then(function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            SystemService.setUID(data.returnValue._id);
                            SystemService.setUser(data.returnValue);
                            deferred.resolve(data.returnValue);//执行到这里时，改变deferred状态为执行成功，返回data为从后台取到的数据
                        }
                        else
                            deferred.reject(data.errorReason);
                    }
                )
                .catch(
                    function (data, status, headers, config) {
                        deferred.reject(data);//执行到这里时，改变deferred状态为执行失败，返回data为报错
                    }
                );
            return deferred.promise;

        };
        this.logout = function () {

        };
        this.register = function (user) {

            let param = {

                "name": user.name,
                "studentID": user.studentID,
                "pwdText": user.pwdText,
                "email": user.email,
                "mobile": user.mobile,
                "sex": user.sex


            };
            console.log(param);

            var deferred = $q.defer();//生成deferred异步对象
            $http.post(SystemService.getHostIP() + '/users/register', param)//封装好的param传给后台
                .then(function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            SystemService.setUID(data.returnValue._id);
                            SystemService.setUser(data.returnValue);
                            deferred.resolve(data.returnValue);//执行到这里时，改变deferred状态为执行成功，返回data为从后台取到的数据

                        }
                        else
                            deferred.reject(data.errorReason);
                    }
                )
                .catch(
                    function (data, status, headers, config) {
                        deferred.reject(data);//执行到这里时，改变deferred状态为执行失败，返回data为报错
                    }
                );
            return deferred.promise;//控制异步运行完成
            //return deferred.promise起到保护作用，不允许函数外部改变函数内的deferred状态


        };
        this.getInformation = function () {
            let param = {
                "userId": SystemService.getUID()

            };
            console.log(param);
            var deferred = $q.defer();//生成deferred异步对象
            $http.post(SystemService.getHostIP() + '/users/getInformation', param)//封装好的param传给后台
                .then(
                    function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            deferred.resolve(data.returnValue);//执行到这里时，改变deferred状态为执行成功，返回data为从后台取到的数据

                        }

                        else {
                            deferred.reject(data.errorReason)
                        }
                    }
                )
                .catch(
                    function ({data, status, headers, config}) {
                        deferred.reject(data);//执行到这里时，改变deferred状态为执行失败，返回data为报错
                    }
                );
            return deferred.promise;

        }
        this.Keep = function (time, weekday) {
            let param = {
                "userId": SystemService.getUID(),
                "day": weekday,
                "mons": time.mons,
                "mone": time.mone,
                "afts": time.afts,
                "afte": time.afte,
                "eves": time.eves,
                "evee": time.evee
            };
            console.log(param);
            var deferred = $q.defer();//生成deferred异步对象
            $http.post(SystemService.getHostIP() + '/timetable/saveAndUpdateTimetableForApp', param)//封装好的param传给后台
                .then(
                    function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            deferred.resolve(data.returnValue);//执行到这里时，改变deferred状态为执行成功，返回data为从后台取到的数据

                        }

                        else {
                            deferred.reject(data.errorReason)
                        }
                    }
                )
                .catch(
                    function ({data, status, headers, config}) {
                        deferred.reject(data);//执行到这里时，改变deferred状态为执行失败，返回data为报错
                    }
                );
            return deferred.promise;//控制异步运行完成
            //return deferred.promise起到保护作用，不允许函数外部改变函数内的deferred状态


        };
        this.doResetPwd = function (resetPwd, resetPwd2) {
            let param = {
                "userId": SystemService.getUID(),
                "newPwd": resetPwd,
                "newPwd2": resetPwd2
            };
            console.log(param);
            var deferred = $q.defer();//生成deferred异步对象
            $http.post(SystemService.getHostIP() + '/users/changePwd', param)//封装好的param传给后台
                .then(
                    function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            deferred.resolve(data.returnValue);//执行到这里时，改变deferred状态为执行成功，返回data为从后台取到的数据

                        }

                        else {
                            deferred.reject(data.errorReason)
                        }
                    }
                )
                .catch(
                    function ({data, status, headers, config}) {
                        deferred.reject(data);//执行到这里时，改变deferred状态为执行失败，返回data为报错
                    }
                );
            return deferred.promise;


        };
        this.getTimeTable = function () {
            let param = {
                "userId": SystemService.getUID()
            };
            console.log(param);
            var deferred = $q.defer();//生成deferred异步对象
            $http.post(SystemService.getHostIP() + '/timetable/getTimetable', param)//封装好的param传给后台
                .then(
                    function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            deferred.resolve(data.returnValue);//执行到这里时，改变deferred状态为执行成功，返回data为从后台取到的数据

                        }

                        else {
                            deferred.reject(data.errorReason)
                        }
                    }
                )
                .catch(
                    function ({data, status, headers, config}) {
                        deferred.reject(data);//执行到这里时，改变deferred状态为执行失败，返回data为报错
                    }
                );
            return deferred.promise;

        }


    })
    .service('AdminService',function ($q, $http, SystemService) {
        this.getStudentMessage=function(weekday,periodStart) {
            let param = {
                "day": weekday,
                "time": periodStart
            };
            if(param.day=="Monday")
                param.day="Mon";
            else if(param.day=="Sunday")
                param.day="Sun";
            else if(param.day=="Tuesday")
                param.day="Tue";
            else if(param.day=="Wednesday")
                param.day="Wed";
            else if(param.day=="Thursday")
                param.day="Thur";
            else if(param.day=="Friday")
                param.day="Fri";
            else {
                param.day="Sat";
            }
            console.log(param);
            var deferred = $q.defer();//生成deferred异步对象
            $http.post(SystemService.getHostIP() + '/timetable/getTimeIDForApp', param)//封装好的param传给后台
            //从后端获取满足星期一上午开始和结束时间都不为零的，user_id、morningStart、morningEnd
                .then(
                    function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            deferred.resolve(data.returnValue);//执行到这里时，改变deferred状态为执行成功，返回data为从后台取到的数据

                        }

                        else {
                            deferred.reject(data.errorReason)
                        }
                    }
                )
                .catch(
                    function ({data, status, headers, config}) {
                        deferred.reject(data);//执行到这里时，改变deferred状态为执行失败，返回data为报错
                    }
                );
            return deferred.promise;
        };
        /*this.getStudentName=function(ID){
            let param={
                "userId":ID
            };
            console.log(param);
            var deferred = $q.defer();//生成deferred异步对象
            $http.post(SystemService.getHostIP() + '/users/getStudentNameForApp', param)
                .then(
                    function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            deferred.resolve(data.returnValue);//执行到这里时，改变deferred状态为执行成功，返回data为从后台取到的数据

                        }

                        else {
                            deferred.reject(data.errorReason)
                        }
                    }
                )
                .catch(
                    function ({data, status, headers, config}) {
                        deferred.reject(data);//执行到这里时，改变deferred状态为执行失败，返回data为报错
                    }
                );
            return deferred.promise;
        }*/
        this.add = function (groupName) {
            let param = {
                    "name": groupName
                };

            const deferred = $q.defer();
            $http.post(SystemService.getHostIP() + '/group/addGroup', param)
                .then(function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            deferred.resolve(data.returnValue);
                        }
                        else
                            deferred.reject(data.errorReason);
                    }
                )
                .catch(
                    function (data, status, headers, config) {
                        deferred.reject(data);
                    }
                );
            return deferred.promise;

            // $http.get('http://localhost:3030/data')
            //     .then(function (res) {
            //         const data = res.data;
            //         console.log(data);
            //         if (data.code === 0) {
            //             deferred.resolve(data.returnValue);
            //         }
            //         else
            //             deferred.reject(data.errorReason);
            //     });
            // return deferred.promise;


        };

        this.delete = function(group){
            let param = {
                "_id": group._id
            };
            console.log(param._id);
            var deferred = $q.defer();
            $http.post(SystemService.getHostIP() + '/group/deleteGroup',param)
                .then(function (res){
                    const data = res.data;
                    if(data.code == 0){
                        deferred.resolve(data.returnValue);
                    }
                    else
                        deferred.resolve(data.errorReason);
                })
                .catch(
                    function (data,status,headers,config) {
                        deferred.reject(data);

                    }
                );
            return deferred.promise;

        };

        this.editGroupName = function (group,groupName) {
            let param = {
                "name" : groupName,
                "_id" : group._id,
            }
            var deferred = $q.defer();
            $http.post(SystemService.getHostIP() + '/group/updateGroup',param)
                .then(function (res) {
                    const data = res.data;
                    if(data.code === 0 ){
                        deferred.resolve(data.returnValue);
                    }
                    else
                        deferred.reject(data.errorReason);

                })
                .catch(
                    function (data){
                        deferred.reject(data);
                    }
                );
            return deferred.promise;

        };

        this.getName = function () {
            var deferred = $q.defer();
            $http.post(SystemService.getHostIP() + '/group/getGroup')
                .then(function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            deferred.resolve(data.returnValue);
                        }
                        else
                            deferred.reject(data.errorReason);
                    }
                )
                .catch(
                    function (data, status, headers, config) {
                        deferred.reject(data);
                    }
                );

            //
            // $http.get('http://localhost:3030/data')
            //     .then(function (res) {
            //         const data = res.data;
            //         console.log(data);
            //         if (data.code === 0) {
            //             deferred.resolve(data.returnValue);
            //         }
            //         else
            //             deferred.reject(data.errorReason);
            //     });
            return deferred.promise;

        };
    })
    .service('GroupMemberService',function ($q, $http, SystemService) {



        this.getGroupMembers = function (group) {
            let param = {
                "gId": group._id,
            };

            const deferred = $q.defer();
            $http.post(SystemService.getHostIP() + '/group/getGroupMember', param)
                .then(function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            deferred.resolve(data.returnValue);
                        }
                        else
                            deferred.reject(data.errorReason);
                    }
                )
                .catch(
                    function (data, status, headers, config) {
                        deferred.reject(data);
                    }
                );
            return deferred.promise;

            // $http.get('http://localhost:3030/data')
            //     .then(function (res) {
            //         const data = res.data;
            //         console.log(data);
            //         if (data.code === 0) {
            //             deferred.resolve(data.returnValue);
            //         }
            //         else
            //             deferred.reject(data.errorReason);
            //     });
            // return deferred.promise;


        };
        this.getNotMember = function (group) {
            let param = {
                "gId": group._id,
            };

            const deferred = $q.defer();
            $http.post(SystemService.getHostIP() + '/group/getNotGroupMember', param)
                .then(function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            deferred.resolve(data.returnValue);
                        }
                        else
                            deferred.reject(data.errorReason);
                    }
                )
                .catch(
                    function (data, status, headers, config) {
                        deferred.reject(data);
                    }
                );
            return deferred.promise;




        };

        this.getNotMemberButAdmin = function (group) {
            let param = {
                "gId": group._id,
            };

            const deferred = $q.defer();
            $http.post(SystemService.getHostIP() + '/group/getNotGroupMemberButAdmin', param)
                .then(function (res) {
                        const data = res.data;
                        console.log(data);
                        if (data.code === 0) {
                            deferred.resolve(data.returnValue);
                        }
                        else
                            deferred.reject(data.errorReason);
                    }
                )
                .catch(
                    function (data, status, headers, config) {
                        deferred.reject(data);
                    }
                );
            return deferred.promise;




        };
        this.deleteGroupMember = function(group,member){
            let param = {
                "gId": group._id,
                "mName" : member.name,
                "mId" : member._id
            };
            console.log(param);
            var deferred = $q.defer();
            $http.post(SystemService.getHostIP() + '/group/deleteGroupMember',param)
                .then(function (res){
                    const data = res.data;
                    if(data.code == 0){
                        deferred.resolve(data.returnValue);
                    }
                    else
                        deferred.reject(data.errorReason);
                })
                .catch(
                    function (data,status,headers,config) {
                        deferred.reject(data);

                    }
                );
            return deferred.promise;

        };

        this.addGroupMember = function(group,member){
            let param = {
                "gId": group._id,
                "mName" : member.name,
                "mId" : member._id
            };
            console.log(param);

            var deferred = $q.defer();
            $http.post(SystemService.getHostIP() + '/group/addGroupMember',param)
                .then(function (res){
                    const data = res.data;
                    if(data.code == 0){
                        deferred.resolve(data.returnValue);
                    }
                    else
                        deferred.reject(data.errorReason);
                })
                .catch(
                    function (data,status,headers,config) {
                        deferred.reject(data);

                    }
                );
            return deferred.promise;

        };
    })
    .service('MusicTagService',function ($q,$http,SystemService) {
        this.addTag = function(name,tag1, tag2,tag3,tag4){
            let param = {
                "name":name,
                "tag1" :tag1,
                "tag2" :tag2,
                "tag3" :tag3,
                "tag4" :tag4
            };
            console.log(param);

            var deferred = $q.defer();
            $http.post(SystemService.getHostIP() + '/tag/addTag',param)
                .then(function (res){
                    const data = res.data;
                    if(data.code == 0){
                        deferred.resolve(data.returnValue);
                    }
                    else
                        deferred.reject(data.errorReason);
                })
                .catch(
                    function (data,status,headers,config) {
                        deferred.reject(data);

                    }
                );
            return deferred.promise;

        };



        
    })
;